package com.itheima.dbsharding.month.algorithm;

import com.google.common.collect.Range;
import com.itheima.dbsharding.month.tool.DateUtils;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;

/**
 * @author jiangta
 * @version 1.0
 * @date 2020/5/8 11:42 上午
 */
public class MonthRangeAlgorithm implements RangeShardingAlgorithm<Date> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        System.out.println("collection:" + collection + " RangeShardingValue:"+ rangeShardingValue);
        Collection<String> result = new LinkedHashSet<String>();
        Range<Date> shardingKey = rangeShardingValue.getValueRange();
        Date startShardingKey = shardingKey.lowerEndpoint();
        Date endShardingKey = shardingKey.upperEndpoint();

        LocalDateTime startLocalDate = DateUtils.UDateToLocalDateTime(startShardingKey);
        LocalDateTime endLocalDate = DateUtils.UDateToLocalDateTime(endShardingKey);

        //进行判断 获取跨月份的表 如201901,201902,201903 三个月的表
        DateTimeFormatter dateformat = DateTimeFormatter.ofPattern("yyyyMM");
        int end = Integer.valueOf(dateformat.format(endLocalDate));
        int start = Integer.valueOf(dateformat.format(startLocalDate));
        while (start < end) {
            StringBuffer tableName = new StringBuffer();
            tableName.append(rangeShardingValue.getLogicTableName())
                    .append("_").append(start);
            result.add(tableName.toString());
            start++;
        }
        return result;
    }
}
